<?php
abstract class MFormElement extends MHtmlElement {
    /**
     * @var MForm
     */
    protected $_form;
    protected $_required;
    protected $_label;
    protected $_value;

    public function __construct($name, $form) {
        $this->_required = true;
        $this->_label = '';
        $this->_value = '';
        $this->setHtmlOption('name', $name);
        $this->_form = $form;
    }

    public function isValid($value){
        $value = $this->getCleanedValue($value);
        $valid = true;
        if ($this->_required && empty($value)){
            $this->_form->addError(__t('mandrill.web.form.elementRequired', array('elementLabel'=>$this->_label)));
            $valid = false;
        }
        if (isset($this->_htmlOptions['maxlength']) && (strlen($value) > $this->_htmlOptions['maxlength'])){
            $this->_form->addError(__t('mandrill.web.form.elementMaxLength', array('elementLabel'=>$this->_label)));
            $valid = false;
        }
        return $valid;
    }

    public function getCleanedValue($value){
        return $value;
    }

    public function setDisabled($disabled = true){
        ($disabled)?$this->setHtmlOption('disabled', 'disabled'):$this->removeHtmlOption('disabled');
        return $this;
    }

    public function setReadOnly($readonly = true){
        ($readonly)?$this->setHtmlOption('readonly', 'readonly'):$this->removeHtmlOption('readonly');
        return $this;
    }

    public function setMaxLength($value){
        (is_int($value) && $value > 0)?$this->setHtmlOption('maxlength', $value):$this->removeHtmlOption('maxlength');
        return $this;
    }

    public function getForm() {
        return $this->_form;
    }

    public function setForm($_form) {
        $this->_form = $_form;
        return $this;
    }

    public function isRequired() {
        return $this->_required;
    }

    public function setRequired($_required) {
        $this->_required = $_required;
        return $this;
    }

    public function getLabel() {
        return $this->_label;
    }

    public function setLabel($_label) {
        $this->_label = $_label;
        return $this;
    }

    public function getValue() {
        return $this->_value;
    }

    public function setValue($_value) {
        $this->_value = $_value;
        return $this;
    }

    abstract public function render();

    public function __toString() {
        return $this->render();
    }
}
?>
